package main.java.com.yc.navy.snacknet.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class RequestParamUtul {
	public static <T> T getParams(Class<T> cls, HttpServletRequest request) {
		T t = null;
		
		try {
			t = cls.newInstance();//实例化一个这个类型的对象
			
			//
			//
			Enumeration<String> names = request.getParameterNames();
			
			//
			Method[] methods = cls.getDeclaredMethods();
			Map<String, Method> setters = new HashMap<String, Method>();
			String methodName = null;
			
			for(Method method : methods) {
				methodName = method.getName();
				if(methodName.startsWith("set")) {
					setters.put(methodName, method);
				}
			}
			
			String name = null;
			Method method = null;
			Class<?>[] types = null;
			Class<?> type = null;
 			String value = null;
 			
 			//
 			while(names.hasMoreElements()) {
 				name = names.nextElement();
 				
 				//
 				methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
 				method = setters.get(methodName);
 				if(method == null) {
 					continue;
 				}
 				types = method.getParameterTypes();
 				if(types == null || types.length < 0) {
 					continue;
 				}
 				type = types[0];
 				value = request.getParameter(name);
 				if(type == Integer.TYPE) {
 					method.invoke(t, Integer.parseInt(value));
 					continue;
 				}
 				if(type == Integer.class) {
 					method.invoke(t, Integer.valueOf(value));
 					continue;
 				}
 				if(type == Long.TYPE) {
 					method.invoke(t, Integer.parseInt(value));
 					continue;
 				}
 				if(type == Long.class) {
 					method.invoke(t, Long.parseLong(value));
 					continue;
 				}
 				if(type == Double.TYPE) {
 					method.invoke(t, Double.parseDouble(value));
 					continue;
 				}
 				if(type == Double.class) {
 					method.invoke(t, Double.parseDouble(value));
 					continue;
 				}
 				method.invoke(t, value);
 			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return t;	
	}
}
